<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Crypt;
class LoginController extends Controller
{
    //
    public function login()
    {
    	return view('admin.login.login');
    }
    
     public function logout()
    {
    	session() -> forget('master1');
    	return redirect('/admin/login');
    }

    public function dologin(Request $request)
    {
    	//验证用户名、密码
    	$this -> validate($request, [
    		'adminName' => 'required',
    		'password' => 'required'
    		], [
    		'adminName.required' => '用户名不能为空',
    		'password.required' => '密码不能为空',
    		]);

    	$scode = session('milkcaptcha');
    	$rcode = $request -> input('captcha');

    	if($scode != $rcode)
    	{
    		return back() -> with(['info' => '验证码不正确']);
    	}   	


    	//获取
    	$data = $request -> except('_token');
    	// 查询       
      if($data['accountid']==1)
      {
        $res = DB::table('users_admin') -> where('username', $data['adminName']) -> first();
      }else
      {
         $res = DB::table('users_edit') -> where('username', $data['adminName']) -> first();         
      }

      
        if(!$res)
        {
            return back() -> with(['info' => '账号或密码错误']);
        }
             
    	// 解密
    	$password = Crypt::decrypt($res -> password);
    	//判断
       
    	if($password != $data['password'])
    	{
    		return back() -> with(['info' => '账号或密码错误']);
    	}
    	// 存入seesion
    	session(['master1' => $res ]);
        
        // 写入最后登录时间
        // 
        $ltime = time();
        if($data['accountid']==1)
          {
             DB::table('users_admin') -> where('username', $data['adminName']) -> update(['ltime' => $ltime]);
          }else
          {
            DB::table('users_edit') -> where('username', $data['adminName']) -> update(['ltime' => $ltime]);
          }
        
       
    	return redirect('/admin/index') -> with(['info' => '登录成功']);
    }
}
